﻿/*
using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Core;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Reflection;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Threading;
using WPFExcelReport.Helpers;
namespace WPFExcelReport
{
    public partial class ApplicationBase
    {
        public static readonly ApplicationBase Instance = new ApplicationBase();
        string SvcAdr = "HTTP";
        public ApplicationBase()
        {
            myHashtable = CheckExcellProcesses();
            KillExcel(myHashtable);
        }
        public bool Connected
        {
            get;
            set;
        }
        public bool IsHelp
        {
            get;
            set;
        }
        public bool IsTranslate
        {
            get;
            set;
        }
        public void Quit()
        {
            try
            {
                Dictionary<string, object> a = new Dictionary<string, object>();
                a.Add("QAGENT", proxyInstance.AgentID);
                proxy.RequestAgentStart(a);
            }
            catch (Exception ex)
            { }
        }
        ~ApplicationBase()
        {
            if (proxy.State != System.ServiceModel.CommunicationState.Closed)
            {
                proxy.Close();
            }
        }

        public log4net.ILog m_log_out = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private Dictionary<string, object> EnvExe;
        public Dictionary<string, object> dicParamater
        {
            get
            {
                return EnvExe;
            }
        }
        public OracleConnection OracleDB
        {
            get;
            set;
        }

        public INTEXDBC INTEXDBC
        {
            get;
            set;
        }
        public INTEXBL INTEXBL
        {
            get;
            set;
        }
        public ITXDB INTEXDB = new ITXDB();
        public string Updater
        {
            get
            {
                return (string)EnvExe["Updater"];
            }

        }
        public DataTable UserTable
        {
            get
            {
                return INTEXDB.Tables["ICC_MENUDEF"];
            }
        }
        public string company
        {
            get
            {
                return (string)EnvExe["Company"];
            }
        }
        public string INTEXSYS
        {
            get
            {
                return (string)EnvExe["dbSystem"];
            }
        }
        public string DBUSER
        {
            get
            {
                return (string)EnvExe["dbUser"];
            }
        }
        public string DBPWD
        {
            get
            {
                return (string)EnvExe["dbPwd"];
            }
        }
        public string SQLDB
        {
            get
            {
                return (string)EnvExe["SqlDB"];
            }
        }
        public string LANG
        {
            get
            {
                return (string)EnvExe["LANG"];
            }
            set
            {
                EnvExe["LANG"] = value;
            }
        }
        string CHECKFOLDER = "NO";
        public string SqlDB
        {
            get
            {
                return (string)EnvExe["SqlDB"];
            }
        }
        public string ROOTDRIVE
        {
            get
            {
                return (string)EnvExe["ROOTDRIVE"];
            }
        }
        public string SubFolders
        {
            get
            {
                return (string)EnvExe["SubFolders"];
            }
        }
        public string DocType
        {
            get
            {
                return (string)EnvExe["DocType"];
            }
        }
        public string User
        {
            get
            {
                return (string)EnvExe["User"];
            }
            set
            {
                EnvExe["User"] = value;
            }
        }
        public bool BYAGENT
        {
            get
            {
                if (EnvExe.ContainsKey("BYAGENT"))
                {
                    if ((string)EnvExe["BYAGENT"] == "NO")
                        return false;
                }
                return true;
            }
        }

        public string Pwd
        {
            get
            {
                return (string)EnvExe["Pwd"];
            }
        }
        public string Mandant
        {
            get
            {
                return (string)EnvExe["MANDANT"];
            }
        }
        Hashtable myHashtable;
        public string ApplicationPath
        {
            get { return System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath); }
        }
        public string lib
        {
            get { return System.IO.Directory.GetParent(ApplicationPath) + "\\Lib"; }
        }
        public string LayoutFile
        {
            get { return System.IO.Path.Combine(ApplicationPath, "IntexReportClient.Layout.xml"); }
        }
        private SynchronizationContext _uiSyncContext = null;
        InstanceContext _context = null;
        public InstanceContext Context
        {
            get
            {
                return _context;
            }
        }
        public void Load()
        {
            try
            {
                _context = new InstanceContext(this);
                _uiSyncContext = SynchronizationContext.Current;
                IsHelp = false;
                IsTranslate = false;
                EnvExe = new Dictionary<string, object>();
                ReadConfig(ref EnvExe); 
                if (EnvExe.ContainsKey("ISCALLBACK"))
                {
                    if (EnvExe["ISCALLBACK"].ToString() == "YES")
                    {
                        IsCallBack = true;
                        SvcAdr = "DUALHTTP";
                    }
                }   
                proxyInstance = new IntexReptServBLClient(Context, SvcAdr); 
                EnvExe.Add("m_log_out", m_log_out);
                EnvExe.Add("proxy", proxy);
                Connect2DB(INTEXSYS, DBUSER, DBPWD);
                INTEXDBC = new INTEXDBC(OracleDB, proxy);
                INTEXBL = new INTEXBL();
                INTEXBL.OracleDB = OracleDB;
                INTEXBL.proxy = proxy;
                Connected = GetID();
                if (!Connected)
                    return;
                INTEXDB.Merge(LoadSetSETUP(company, User));
                EnvExe.Add("blBuildCellMastrix", false);
                EnvExe.Add("_Control", this);
                EnvExe.Add("dsParamaters", null);
                EnvExe.Add("ExCelNameMatrix", null);
                EnvExe.Add("USERRIGHT", null);
                EnvExe.Add("ApplicationBase", this);
                EnvExe.Add("ActiveDocument", null);
                EnvExe.Add("LANG", "SCN");
                if (INTEXDB.Tables.Contains("ICC_HRSTAMM"))
                {
                    if (INTEXDB.Tables["ICC_HRSTAMM"].Rows.Count > 0)
                    {
                        DataRow dwUser = INTEXDB.Tables["ICC_HRSTAMM"].Rows[0];
                        EnvExe["ExcelFile"] = Path.Combine(PathHelper.ApplicationPath, @"Report\" + company + "\\" + dwUser["EXCELFILE"].ToString().Trim());
                    }
                }
                if (EnvExe.ContainsKey("CHECKFOLDER"))
                {
                    CHECKFOLDER = (string)EnvExe["CHECKFOLDER"];
                }
                EnvExe["ExcelFile"] = Path.Combine(PathHelper.ApplicationPath, @"Report\" + company + "\\" + EnvExe["ExcelFile"].ToString().Trim());
                StartListen();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                if (Connected)
                {
                    Tracer.Info("登陆", User + company + proxyInstance.AgentID + "登录成功"); 
                }
                else
                {
                    Tracer.Info("登陆", User + company + proxyInstance.AgentID + "登录失败");
                }
            }
        }

        private void Connect2DB(string intex, string dbuser, string dbpwd)
        { 
            string OracleDBConnString = "user id=" + dbuser
        + ";data source=" + intex
        + ";password=" + dbpwd + ";Unicode=True;"
           + "Persist Security Info=True;";
            if (OracleDB != null)
            {
                OracleDB.Close();
            }
            OracleDB = new OracleConnection(OracleDBConnString);
            OracleDB.ConnectionString = OracleDBConnString;
            EnvExe["OracleDB"] = OracleDB;
            EnvExe["OracleDBConnString"] = OracleDBConnString;
            SqlConnection SqlServerDB = new SqlConnection(SQLDB);
            EnvExe["SqlServerDB"] = SqlServerDB;
            EnvExe["SqlServerDBConnString"] = SQLDB;
        }
        private void ReadConfig(ref Dictionary<string, object> env)
        {
            string key = "";
            string value = "";

            bool Found = false;
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            for (int i = 0; i < appSettings.Count; i++)
            {
                key = appSettings.GetKey(i);
                if (key == "ServiceUri")
                {
                    Found = true;
                }
                value = appSettings[i];
                if (env.ContainsKey(key))
                {
                    env[key] = value;
                }
                else
                {
                    env.Add(key, value);
                }
            }
            if (!Found)
            {
                CreateAppSettings();
            }
        }
        // Create the AppSettings section.
        // The function uses the GetSection(string)method 
        // to access the configuration section. 
        // It also adds a new element to the section collection.
        public static void CreateAppSettings()
        {
            // Get the application configuration file.
            System.Configuration.Configuration config =
              ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);
            string newKey = "ServiceUri";
            string newValue = "180.166.130.110";
            config.AppSettings.Settings.Add(newKey, newValue);
            // Save the configuration file.
            config.Save(ConfigurationSaveMode.Modified);
            //config.AppSettings.Settings.Remove();

            ConfigurationManager.RefreshSection("appSettings");

        }

        public Hashtable CheckExcellProcesses()
        {
            Process[] AllProcesses = Process.GetProcessesByName("EXCEL");
            Hashtable myHashtable = new Hashtable();
            int iCount = 0;

            foreach (Process ExcelProcess in AllProcesses)
            {
                myHashtable.Add(ExcelProcess.Id, iCount);
                iCount = iCount + 1;
            }
            return myHashtable;
        }
        public void KillExcel(Hashtable myHashtable)
        {
            Process[] AllProcesses = Process.GetProcessesByName("EXCEL");

            // check to kill the right process
            foreach (Process ExcelProcess in AllProcesses)
            {
                if (myHashtable.ContainsKey(ExcelProcess.Id) == false)
                    ExcelProcess.Kill();
            }

            AllProcesses = null;
        }

        public DataSet ReSetSETUP()
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            DataSet settemp = new DataSet();
            DataSet SResult = LoadSetSETUP(company, User);
            INTEXDB.Merge(SResult);
            return setReturn;
        }

        public DataSet LoadSetSETUP(string company, string user)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            DataRow dwData = null;
            if (!Connected)
            {
                return setReturn;
            }
            dwData = INTEXDB.ICC_QUERYTB.NewRow();
            dwData["MANDANT"] = Mandant;
            dwData["COMPANY"] = company;
            dwData["USERID"] = Helper.Left(User + "    ", 8);
            setResult = INTEXDBC.QueryICC_HRSTAMM(dwData, 2);
            setReturn.Merge(setResult);

            dwData = INTEXDB.ICC_QUERYTB.NewRow();
            dwData["MANDANT"] = Mandant;
            dwData["COMPANY"] = company;
            dwData["USERID"] = Helper.Left(User + "    ", 8);

            setResult = INTEXDBC.QueryICC_MENUDEF(dwData, 2);
            setReturn.Merge(setResult);
            if (CHECKFOLDER == "YES")
            {
                dwData = INTEXDB.ICC_QUERYTB.NewRow();
                dwData["MANDANT"] = Mandant;
                setResult = INTEXDBC.QueryICC_FOLDERS(dwData, 9999);
                foreach (DataRow rowf in setResult.Tables[0].Rows)
                {
                    Helper.CheckDirectory(rowf["ROOT"].ToString(), rowf["SUB"].ToString());
                }
            }
            dwData = INTEXDB.ICC_QUERYTB.NewRow();
            dwData["HRMANDANT"] = Mandant;
            dwData["HRBENID"] = Helper.Left(User + "    ", 8);
            setResult = INTEXDBC.QueryHRSTAMM(dwData, 2);
            IsTranslate = false;
            if (setResult.Tables.Count > 0)
            {
                foreach (DataRow row in setResult.Tables[0].Rows)
                {
                    if (row["HRSPRKZ"].ToString().Trim() == "E")
                    {
                        LANG = "EN";
                        IsTranslate = true;
                    }
                }
            }
            return setReturn;
        }
        public void LoadAssembly(ArrayList namelist)
        {
            foreach (var name in namelist)
            {
                LoadAssembly((string)name);
            }
        }
        public Assembly LoadAssembly(string name)
        {
            string root = lib;
            string path = "";
            Assembly result = null;
            Assembly assm = null;
            name = name.Trim();
            try
            {
                if (AssemblyManager.ReflectionCache.ProcessedAssemblies.ContainsKey(name))
                    return null;
                if (AssemblyManager.ReflectionCache.CurrentDomainAssemblies.ContainsKey(name))
                {
                    assm = AssemblyManager.ReflectionCache.CurrentDomainAssemblies[name].Assembly;
                }
                else
                {
                    path = Path.Combine(root, name + ".dll");
                    if (!File.Exists(path))
                    {
                        path = Path.Combine(root, name + ".exe");
                        if (!File.Exists(path))
                        {
                            return null;
                        }
                    }
                    assm = Assembly.LoadFrom(path);
                    AssemblyManager.ReflectionCache.AddToCurrentDomain(assm);
                    AssemblyName[] reflist = assm.GetReferencedAssemblies();
                    foreach (AssemblyName ass in reflist)
                    {
                        name = ass.Name;
                        LoadAssembly(name);
                    }
                }

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
                Tracer.Info("LoadAssembly", name + " Failed");
            }
            result = assm;
            return result;
        }
        public void LoadAssembly(Assembly assembly)
        {
            string name = "";
            name = assembly.GetName().Name;
            if (AssemblyManager.ReflectionCache.ProcessedAssemblies.ContainsKey(name))
                return;
            //首先，对于已经加载到内存的dll，无需再次加载。 
            AssemblyManager.ReflectionCache.RefreshCurrentDomain();
        }
        public Type GetDoc(string doctype)
        {

            Assembly assembly;
            Type docType = null;
            EnvExe["DocType"] = doctype;
            string fullname = "";
            string file = "";

            if (INTEXDB.Tables.Contains(company + "USERRIGHT"))
            {
                EnvExe["USERRIGHT"] = INTEXDB.Tables[company + "USERRIGHT"];
            }
            if (doctype == "ITXSETUP")
            {
                file = "ITXSETUP.dll";
                fullname = "WPFExcelReport.ITXSETUP";
            }
            else
            {
                DataRow dwData = INTEXDB.ICC_QUERYTB.NewRow();
                dwData["MANDANT"] = app.Mandant;
                dwData["TYPE"] = Helper.Left(doctype + "                         ", 20);
                DataSet SResult = INTEXDBC.QueryICC_FUNCTIONS(dwData, 2);
                if (SResult.Tables.Count == 0)
                    return docType;
                foreach (DataRow dwFile in SResult.Tables[0].Rows)
                {
                    file = dwFile["FILENAME"].ToString().Trim();
                    fullname = dwFile["NAMESPACE"].ToString().Trim() + "." + dwFile["FULLNAME"].ToString().Trim();
                }
            }
            assembly = LoadAssembly(file.Replace(".dll", ""));
            if (assembly == null)
                return docType;
            docType = assembly.GetType(fullname);

            if (docType == null)
                return docType;
            if (doctype == "ARTICLE")
                EnvExe["blBuildCellMastrix"] = true;

            return docType;
        }
        private Dictionary<string, object> mlDics = new Dictionary<string, object>();
        private Dictionary<string, string> mlDic;
        public void PrepareMulLang(string name)
        {
            name = name.ToUpper();
            if (mlDics.ContainsKey(name))
            {
                mlDic = (Dictionary<string, string>)mlDics[name];
                return;
            }
            mlDic = new Dictionary<string, string>();
            DataRow dwData = INTEXDB.ICC_QUERYTB.NewRow();
            dwData["MANDANT"] = Mandant;
            dwData["MLLOC"] = name;
            if (!Connected)
                return;

            DataSet Result = INTEXDBC.QueryICC_MULLANG(dwData, 2);
            if (Result.Tables.Count > 0)
            {
                foreach (DataRow row in Result.Tables[0].Rows)
                {
                    string key = Helper.GetGB2312Value(row["MLKEY"].ToString().Trim());
                    if (!mlDic.ContainsKey(key))
                    {
                        mlDic.Add(key, Helper.GetGB2312Value(row[LANG].ToString().Trim()));
                    }
                }
            }
            mlDics.Add(name, mlDic);
        }
        public string StartTranslate(string word)
        {
            word = word.Trim();
            if (mlDic.ContainsKey(word))
            {
                return this.mlDic[word];
            }
            else
            {
                return word;
            }
        }
        public DataRow UserValid(string name, string pwd)
        {
            if (!INTEXDB.Tables.Contains("ICC_HRSTAMM"))
                return null;
            string filter = "USERID ='" + Helper.Left(name.PadRight(8), 8) + "' AND PWD='" + Helper.Left(pwd.PadRight(20), 20) + "'";
            DataRow[] rows = INTEXDB.Tables["ICC_HRSTAMM"].Select(filter);
            if (rows.Length > 0)
                return rows[0];
            else
                return null;
        }
    }
    public partial class ApplicationBase : IIntexReptServBLCallback
    {
        string AgentID = "-1";
        bool IsCallBack = false;
        //proxy = new IntexReptServBLClient();
        private IntexReptServBLClient proxyInstance;
        public IntexReptServBLClient proxy
        {
            get
            {
                if (proxyInstance == null)
                {
                    AttemptToConnect();
                }
                return this.proxyInstance;
            }
        }
        public void CheckConnection()
        {
            Connected = GetID();
        }

        public void NotifyClient(string WFHANDLER,string WFID)
        {
            // The UI thread won't be handling the callback, but it is the only one allowed to update the controls.  
            // So, we will dispatch the UI update back to the UI sync context.
            SendOrPostCallback callback =
                delegate(object state)
                {
                    Tracer.Info(AgentID, String.Format("{0} has message.", state.ToString())
                        );
                };

            _uiSyncContext.Post(callback, WFID);
        } 
        public void StartListen()
        {
            if (IsCallBack)
            {
                proxy.StartAgentListen(new Dictionary<string, object>());
            }
        }
        public bool GetID()
        {
            bool IsSuccess = true;
            proxy.BYAGENT = BYAGENT;
            DataSet SResult;
            SResult = proxyInstance.RequestAgentStart(new Dictionary<string, object>());
            if (SResult.Tables.Count == 0)
            {
                IsSuccess = false;
                return IsSuccess;
            }
            foreach (DataRow row in SResult.Tables[0].Rows)
            {
                AgentID = row["AGENTID"].ToString();
                DataRow dwData = INTEXDB.ICC_QUERYTB.NewRow();
                dwData["HRMANDANT"] = Mandant;
                DataSet SetUser = INTEXDBC.QueryHRSTAMM(dwData, 5);
                int license = 9999;
                int online = 0;
                foreach (DataRow rhr in SetUser.Tables[0].Rows)
                {
                    string ls = rhr["HRDTELD"].ToString();
                    if (ls.Trim() == "")
                        license = 0;
                    else
                    {
                        license = Convert.ToInt16(ls);
                    }
                    if (license == 0)
                    {
                        license = 9999;
                    }
                    string on = rhr["DB11"].ToString();
                    if (on.Trim() == "")
                        online = 0;
                    else
                    {
                        online = Convert.ToInt16(on);
                    }
                }
                if (SResult.Tables[0].Columns.Contains("USERS"))
                {
                    int reportusers = Convert.ToInt16(row["USERS"].ToString());
                    if (license - (reportusers + online) > -1)
                    {
                        AgentID = row["AGENTID"].ToString();
                        Tracer.Info("AgentID" + proxyInstance.AgentID + ",intex 用户:" + online + "，报表用户：" + reportusers, ",申请成功");
                    }
                    else
                    {
                        IsSuccess = false;
                        Tracer.Info("ApplicationBase.AgentID", "申请不成功");
                        return IsSuccess;
                    }
                }
            }
            proxyInstance.AgentID = AgentID;
            return IsSuccess;
        }
        private void ProxyChannelFaulted(object sender, EventArgs e)
        {
            bool connected = false;
            while (!connected)
            {
                // you may want to put timer code around this, or 
                // other code to limit the number of retrys if 
                // the connection keeps failing
                AttemptToConnect();
            }
        }
        public bool AttemptToConnect()
        {
            // this whole process needs to be thread safe
            lock (proxyInstance)
            {
                try
                {

                    if (proxyInstance != null)
                    {
                        // deregister the event handler from the old instance
                        proxyInstance.InnerChannel.Faulted -= new EventHandler(ProxyChannelFaulted);
                    }
                    proxyInstance = new IntexReptServBLClient(Context, SvcAdr);
                    // always open the connection
                    proxyInstance.Open();

                    // add the event handler for the new instance
                    // the client faulted is needed to be inserted here (after the open)
                    // because we don't want the service instance to keep faulting (throwing faulted event)
                    // as soon as the open function call.
                    proxyInstance.InnerChannel.Faulted += new EventHandler(ProxyChannelFaulted); 

                    return true;
                }
                catch (EndpointNotFoundException ex)
                {
                    Tracer.Error(ex.StackTrace, ex);
                    return false;
                }
                catch (TimeoutException ex)
                {
                    Tracer.Error(ex.StackTrace, ex);
                    // do something here (log, show user message etc.)
                    return false;
                }
            }
        }


    }
}
*/